package com.mao.dao.common;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Component;

import com.mao.dao.BaseDAOHibernate;
import com.mao.service.common.ValDelOrgProWhCondition;
import com.mao.util.MakeOrderNo;

@Component("commonDao")
public class CommonDao extends BaseDAOHibernate{

	public String getVoucherNo(long storeid, String type, String tableName) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String nowdate = sdf.format(new Date());
		Long now = Long.parseLong(nowdate); 
		String likeNO = type + storeid + now;
		Session session = this.getSession();
		String hql = "from " + tableName +  " t where t.voucherNo like '" + likeNO + "%'";
		Query query = session.createQuery(hql);
		Integer usedqty = query.list().size();
		return MakeOrderNo.getOrderNo(storeid, type ,usedqty);
	}
	
	/**
	 * 
	 *  Created on 2012-11-16 
	 * <p>Discription:[判断商品仓库往来单位是否能删除]</p>
	 * @author:[沈晓超]
	 * @update:[日期2012-11-16] [沈晓超]
	 * @param vop
	 * @return
	 * @return String
	 */
	public String valDelOrgProWH(ValDelOrgProWhCondition vop) {
		Session session = this.getSession();
		StringBuilder sb = new StringBuilder();
		sb.append("From ProductDeliveryVoucher pv where 1=1");
		parseDelOrgProWHHql(vop,sb);
		Query query = session.createQuery(sb.toString());
		if(query.list().size() > 0){
			return "no";
		}
		sb = new StringBuilder();
		sb.append("From ProductReturnDeliveryVoucher pv where 1=1");
		parseDelOrgProWHHql(vop,sb);
		query = session.createQuery(sb.toString());
		if(query.list().size() > 0){
			return "no";
		}
		sb = new StringBuilder();
		sb.append("From ProductReturnWareHouseVoucher pv where 1=1");
		parseDelOrgProWHHql(vop,sb);
		query = session.createQuery(sb.toString());
		if(query.list().size() > 0){
			return "no";
		}
		sb = new StringBuilder();
		sb.append("From ProductWareHouseVoucher pv where 1=1");
		parseDelOrgProWHHql(vop,sb);
		query = session.createQuery(sb.toString());
		if(query.list().size() > 0){
			return "no";
		}
		return "yes";
 	}
	
	private static void  parseDelOrgProWHHql (ValDelOrgProWhCondition vop,StringBuilder sb){
		if(vop.getPid() != 0) {
			sb.append(" and pv.product.id=" + vop.getPid());
		}
		if(vop.getOrgid() != 0) {
			sb.append(" and pv.voucher.org.id=" + vop.getOrgid());
		}
		if(vop.getWhid() != 0) {
			sb.append(" and pv.voucher.wareHouse.id=" + vop.getWhid());
		}
		if(vop.getUid() != 0) {
			sb.append(" and pv.voucher.user.id=" + vop.getUid());
		}
	}
}
